<template>
  <div class="print-file-upload">
    <el-upload
      multiple
      :disabled="disabled"
      :action="uploadFileUrl"
      :before-upload="handleBeforeUpload"
      :on-success="handleUploadSuccess"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :data="data"
      :limit="limit"
      :file-list="fileList"
      :show-file-list="true"
      :headers="headers"
      ref="fileUpload"
      v-if="!disabled"
    >
      <el-button size="mini" type="primary">选择打印文件</el-button>
      <div class="el-upload__tip" slot="tip" v-if="showTip">
        支持的文件类型：PDF、DOC、DOCX、TXT、JPG、PNG、BMP、TIFF
        <template v-if="fileSize">，大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b></template>
      </div>
    </el-upload>

    <!-- 文件列表 -->
    <transition-group ref="uploadFileList" class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
      <li :key="file.url" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList">
        <el-link :href="`${baseUrl}${file.url}`" :underline="false" target="_blank">
          <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
        </el-link>
        <div class="ele-upload-list__item-content-action">
          <el-link :underline="false" @click="handleDelete(index)" type="danger" v-if="!disabled">删除</el-link>
        </div>
      </li>
    </transition-group>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth"
import Sortable from 'sortablejs'

export default {
  name: "PrintFileUpload",
  props: {
    // 值
    value: [String, Object, Array],
    // 上传接口地址
    action: {
      type: String,
      default: "/print/file/upload"
    },
    // 上传携带的参数
    data: {
      type: Object
    },
    // 数量限制
    limit: {
      type: Number,
      default: 5
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 50
    },
    // 文件类型
    fileType: {
      type: Array,
      default: () => ["pdf", "doc", "docx", "txt", "jpg", "jpeg", "png", "bmp", "tiff"]
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    },
    // 禁用组件（仅查看文件）
    disabled: {
      type: Boolean,
      default: false
    },
    // 拖动排序
    drag: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      number: 0,
      uploadList: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API + this.action,
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: []
    }
  },
  mounted() {
    if (this.drag && !this.disabled) {
      this.$nextTick(() => {
        const element = this.$refs.uploadFileList?.$el || this.$refs.uploadFileList
        Sortable.create(element, {
          ghostClass: 'file-upload-darg',
          onEnd: (evt) => {
            const movedItem = this.fileList.splice(evt.oldIndex, 1)[0]
            this.fileList.splice(evt.newIndex, 0, movedItem)
            this.$emit("input", this.listToString(this.fileList))
          }
        })
      })
    }
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          // 首先将值转为数组
          let list = []
          if (Array.isArray(val)) {
            list = val
          } else if (typeof val === 'string') {
            // 如果是字符串则分割
            list = val.split(',')
          } else if (typeof val === 'object') {
            list = [val]
          }
          // 然后将数组转为对象数组
          this.fileList = list.map(item => {
            if (typeof item === 'string') {
              return { name: item, url: item }
            } else {
              return item
            }
          })
        } else {
          this.fileList = []
        }
      },
      immediate: true
    }
  },
  computed: {
    showTip() {
      return this.isShowTip && !this.disabled
    }
  },
  methods: {
    // 文件上传前的钩子
    handleBeforeUpload(file) {
      // 校验文件类型
      let extension = file.name.substring(file.name.lastIndexOf('.') + 1)
      let isType = this.fileType.indexOf(extension) > -1
      if (!isType) {
        this.$modal.msgError(`文件格式不正确，请上传${this.fileType.join("/")}格式文件!`)
        return false
      }
      // 校验文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`)
          return false
        }
      }
      this.$modal.loading("正在上传文件，请稍候...")
      this.number++
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`)
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList.push({ name: res.data.fileName, url: res.data.fileUrl })
        this.uploadedSuccessfully()
      } else {
        this.number--
        this.$modal.closeLoading()
        this.$modal.msgError(res.msg)
        this.$refs.fileUpload.handleRemove(file)
        this.uploadedSuccessfully()
      }
    },
    // 删除文件
    handleDelete(file) {
      const findex = this.fileList.map(f => f.name).indexOf(file.name)
      if (findex > -1) {
        this.fileList.splice(findex, 1)
        this.$emit("input", this.listToString(this.fileList))
      }
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传文件失败，请重试")
      this.$modal.closeLoading()
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList)
        this.uploadList = []
        this.number = 0
        this.$emit("input", this.listToString(this.fileList))
        this.$modal.closeLoading()
      }
    },
    // 列表转字符串
    listToString(list) {
      let strs = []
      list.forEach(item => {
        if (typeof item === 'string') {
          strs.push(item)
        } else {
          strs.push(item.url)
        }
      })
      return strs.join(',')
    },
    // 获取文件名
    getFileName(name) {
      if (name.lastIndexOf('/') > -1) {
        return name.substring(name.lastIndexOf('/') + 1)
      } else {
        return name
      }
    }
  }
}
</script>

<style scoped>
.print-file-upload {
  width: 100%;
}

.upload-file-list {
  margin-top: 10px;
}

.el-upload-list__item {
  transition: all 0.5s cubic-bezier(0.55, 0, 0.1, 1);
}

.file-upload-darg {
  opacity: 0.5;
  background: #c0c4cc;
  border: 2px dashed #606266;
}

.ele-upload-list__item-content-action {
  margin-left: 10px;
}
</style> 